package com.codeape.number.ui;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.codeape.number.R;
import com.codeape.number.base.mvvm.command.Command;
import com.codeape.number.common.view.XPageChangeListener;
import com.codeape.number.databinding.ActivityMainBinding;
import com.codeape.number.ui.main.fragment.divination.DivinationFragment;
import com.codeape.number.ui.main.fragment.record.RecordFragment;
import com.codeape.number.util.CommonUtils;
import com.codeape.number.util.DatabaseUtils;
import com.codeape.number.util.StatusBarUtil;

import java.util.ArrayList;

/**
 * 主页
 *
 * @author LiuPeiming
 */
public class MainActivity extends AppCompatActivity {

    long exitTime = 0;

    ActivityMainBinding mBinding = null;

    final ArrayList<Fragment> fragments = new ArrayList<>();

    public ObservableInt picturePosition = new ObservableInt();
    public ObservableField<PagerAdapter> adapter = new ObservableField<>();
    public ObservableField<ViewPager.OnPageChangeListener> changeListener = new ObservableField<>();

    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //判断设备是否处于深色模式
        if ((getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) != 0) {
            //设置状态栏黑底白字
            StatusBarUtil.changeTitleBarColor(this, ContextCompat.getColor(this, R.color.background));
            StatusBarUtil.setDarkMode(this);
        } else {
            //设置状态栏白底黑字
            StatusBarUtil.changeTitleBarColor(this, ContextCompat.getColor(this, R.color.background));
            StatusBarUtil.setLightMode(this);
        }

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setActivity(this);

        DisplayMetrics dpMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dpMetrics);

        View contentView = LayoutInflater.from(this).inflate(R.layout.pupuwin_menu_item, null);
        popupWindow = new PopupWindow(contentView, dpMetrics.widthPixels / 2, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindow.setOnDismissListener(() -> popupWindow.dismiss());

        contentView.findViewById(R.id.tvClean).setOnClickListener(v -> {
            ((DivinationFragment) fragments.get(0)).binding.getViewModel().toEmptyCommand.execute();
            popupWindow.dismiss();
        });

        contentView.findViewById(R.id.tvHelp).setOnClickListener(v -> {
            startActivity(new Intent(this, HelpActivity.class));
            popupWindow.dismiss();
        });

        initFragment();
        new DatabaseUtils(getApplication());
    }

    /**
     * 显示/隐藏菜单
     */
    public Command onShowOrHideMenu = new Command(() -> {
        CommonUtils.showAsDropDown(popupWindow, mBinding.ivMenu, 0, 0);
    });

    /**
     * 切换占卜Fra
     */
    public Command onDivinationCommand = new Command(() -> picturePosition.set(0));

    /**
     * 切换记录Fra
     */
    public Command onRecordCommand = new Command(() -> picturePosition.set(1));

    private void initFragment() {

        fragments.add(new DivinationFragment());
        fragments.add(new RecordFragment());

        adapter.set(
                new FragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                    @Override
                    public Fragment getItem(int position) {
                        return fragments.get(position);
                    }

                    @Override
                    public int getCount() {
                        return fragments.size();
                    }
                }
        );

        picturePosition.set(0);

        changeListener.set(new XPageChangeListener(this, fragments.size(), picturePosition));

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast toast = new Toast(this);
                toast.setDuration(Toast.LENGTH_LONG);
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.layout_toast, null);
                toast.setView(view);
                toast.show();

                exitTime = System.currentTimeMillis();
            } else {
                finish();
                //System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}